﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media.Imaging;
using ExifLib;
using System.IO;
using Microsoft.Phone.Tasks;
using System.Threading;
using System.Windows.Threading;

namespace BigPicWatcher
{
    public partial class PictureList : PhoneApplicationPage
    {
        public PictureList()
        {
            InitializeComponent();

            GetPictures();
        }

        /// <summary>
        /// Gets Albums from Album collection and adds them to the listing
        /// </summary>
        /// <param name="albumCollection">Collection of Albums</param>
        private void GetPictures()
        {
            var Ablum = App.SelectedAlbum;
            var Pictures = new List<Image>();
            if (Ablum == null || Ablum.Count == 0)
                NavigationService.Navigate(new Uri("/AblumList.xaml", UriKind.RelativeOrAbsolute));

            for (var i = 0; i < Ablum.Count(); i++)
            {
                var picture = Ablum[i];
                Image img = new Image() { Width = 99, Height = 99, Margin = new Thickness(5), Tag = i };
                var bitmap = new BitmapImage();

                imgtmps.Add(new tmpimg() { _num = i, _img = img });
                //using (var source = picture.GetThumbnail())
                //    bitmap.SetSource(source);

                //if (img != null)
                //    img.Source = bitmap;
                img.Tap += (s, e) =>
                {
                    loadingScreen.Visibility = System.Windows.Visibility.Visible;
                    int picnum = (int)(s as Image).Tag;
                    Dispatcher.BeginInvoke(() =>
                    {
                        Stream stream = picture.GetImage();
                        //JpegInfo info = ExifReader.ReadJpeg(stream, picture.Name);
                        var info = new GetPhotoInfo(stream);
                        App.PictureNum = picnum;
                        if (info.photoinfo.Width == 0)
                        {
                            MessageBoxResult m = MessageBox.Show("图片读取失败，是否尝试另一种打开方式？", "失败", MessageBoxButton.OKCancel);
                            if (m == MessageBoxResult.Cancel)
                            {
                                loadingScreen.Visibility = System.Windows.Visibility.Collapsed;
                                return;
                            }
                            else
                            {
                                loadingScreen.Visibility = System.Windows.Visibility.Collapsed;
                                OpenwithTasks();
                            }
                        }
                        else
                        {
                            App.bitmap = new WriteableBitmap(info.photoinfo.Width, info.photoinfo.Height);
                            stream.Position = 0;
                            App.bitmap.LoadJpeg(stream);
                            App.ToViewPage(this);
                        }
                    });
                };
                Pictures.Add(img);
            }
            bind(Pictures);

            //载入图片
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        
        void bind(List<Image> Pictures)
        {
            int i = 0;
            StackPanel sp = new StackPanel();
            List<StackPanel> list = new List<StackPanel>();
            foreach (var item in Pictures)
            {
                if (i == 0)
                {
                    sp = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Horizontal };
                    list.Add(sp);
                }
                sp.Children.Add(item);
                i++;
                if (i == 4) { i = 0; }
            }
            items.ItemsSource = list;
        }

        #region 分开载入图片
        List<tmpimg> imgtmps = new List<tmpimg>();
        public class tmpimg
        {
            public int _num;
            public Image _img;
        }
        DispatcherTimer timer = new DispatcherTimer();
        int loadingpicnum = 0;
        void timer_Tick(object sender, EventArgs e)
        {
            if (imgtmps.Count > 0 && loadingpicnum < 16)//同时最多载入16张
            {
                loadingpicnum++;
                var bitmap = new BitmapImage();
                var Ablum = App.SelectedAlbum;
                var img = imgtmps[0]._img;
                var picture = Ablum[imgtmps[0]._num];
                using (var source = picture.GetThumbnail())
                    bitmap.SetSource(source);

                if (img != null)
                    img.Source = bitmap;
                lock (imgtmps)
                {
                    imgtmps.RemoveAt(0);
                }
                loadingpicnum--;
            }
            if (imgtmps.Count == 0) timer.Stop();
        }

        /// <summary>
        /// 退出时取消异步加载，并释放图片内存
        /// </summary>
        /// <param name="e"></param>
        public void ClearPic()
        {
            timer.Stop();
            foreach (var item in imgtmps)
                item._img.Source = null;
            imgtmps.Clear();
        }
        
        #endregion

        PhotoChooserTask photoChooserTask;
        void OpenwithTasks()
        {
            if (photoChooserTask == null)
            {
                photoChooserTask = new PhotoChooserTask();
                photoChooserTask.Completed += photoChooserTask_Completed;
            }
            photoChooserTask.Show();
        }
        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                JpegInfo info = ExifReader.ReadJpeg(e.ChosenPhoto, e.OriginalFileName);

                App.bitmap = new WriteableBitmap(info.Width, info.Height);
                e.ChosenPhoto.Position = 0;
                App.bitmap.LoadJpeg(e.ChosenPhoto);
                App.ToViewPage(this);
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //清空内存 
            items.ItemsSource = null;
            ClearPic();
            base.OnNavigatedFrom(e);
        }
    }
}